﻿/*******************************************************************************
 * Copyright © 2016
 * 
 * Description: MVC快速开发平台  FROM http://xmwxgn.com
 *
*********************************************************************************/
using ZFine.Domain.Entity.SystemSecurity;
using ZFine.Application.SystemSecurity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZFine.Domain.Entity.SystemManage;
using ZFine.Application.SystemManage;
using ZFine.Code;
using ZFine.Application;
using ZFine.Web.Services;
using ZFine.Application.Gas;
using ZFine.Domain.Entity.Gas;

namespace ZFine.Web.Controllers
{
    public class LoginController : Controller
    {
        private UserApp userApp = new UserApp();
        private RoleApp roleApp = new RoleApp();
        private UserLogOnApp userLogOnApp = new UserLogOnApp();
        private EduConfigApp eduConfigApp = new EduConfigApp();
        private string LoginProvider = Configs.GetValue("LoginProvider");

        [HttpGet]
        public virtual ActionResult Index()
        {
            var test = string.Format("{0:E2}", 1);
            return View();
        }
        [HttpGet]
        public virtual ActionResult Register(string keyValue)
        {
            ViewBag.keyValue = keyValue;
            return View();
        }
        [HttpGet]
        public ActionResult GetAuthCode()
        {
            return File(new VerifyCode().GetVerifyCode(), @"image/Gif");
        }
        [HttpGet]
        public ActionResult OutLogin()
        {
            new LogApp().WriteDbLog(new LogEntity
            {
                F_ModuleName = "系统登录",
                F_Type = DbLogType.Exit.ToString(),
                F_Account = OperatorProvider.Provider.GetCurrent().UserCode,
                F_NickName = OperatorProvider.Provider.GetCurrent().UserName,
                F_Result = true,
                F_Description = "安全退出系统",
            });
            Session.Abandon();
            Session.Clear();
            OperatorProvider.Provider.RemoveCurrent();
            return RedirectToAction("Index", "Login");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult CheckLogin(string username, string password, string code)
        {
            LogEntity logEntity = new LogEntity();
            logEntity.F_ModuleName = "系统登录";
            logEntity.F_Type = DbLogType.Login.ToString();
            try
            {
                if (Session["ZFine_session_verifycode"].IsEmpty() || Md5.md5(code.ToLower(), 16) != Session["ZFine_session_verifycode"].ToString())
                {
                    throw new Exception("验证码错误，请重新输入");
                }

                UserEntity userEntity = new UserApp().CheckLogin(username, password);
                if (userEntity != null)
                {
                    OperatorModel operatorModel = new OperatorModel();
                    operatorModel.UserId = userEntity.F_Id;
                    operatorModel.UserCode = userEntity.F_Account;
                    operatorModel.UserName = userEntity.F_RealName;
                    operatorModel.CompanyId = userEntity.F_OrganizeId;
                    operatorModel.DepartmentId = userEntity.F_DepartmentId;
                    operatorModel.RoleId = userEntity.F_RoleId;
                    operatorModel.LoginIPAddress = Net.Ip;
                    operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress);
                    operatorModel.LoginTime = DateTime.Now;
                    operatorModel.LoginToken = DESEncrypt.Encrypt(Guid.NewGuid().ToString());
                    if (userEntity.F_Account == "admin")
                    {
                        operatorModel.IsSystem = true;
                    }
                    else
                    {
                        operatorModel.IsSystem = false;
                    }
                    OperatorProvider.Provider.AddCurrent(operatorModel);
                    logEntity.F_Account = userEntity.F_Account;
                    logEntity.F_NickName = userEntity.F_RealName;
                    logEntity.F_Result = true;
                    logEntity.F_Description = "登录成功";
                    new LogApp().WriteDbLog(logEntity);
                }
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功。" }.ToJson());
            }
            catch (Exception ex)
            {
                logEntity.F_Account = username;
                logEntity.F_NickName = username;
                logEntity.F_Result = false;
                logEntity.F_Description = "登录失败，" + ex.Message;
                new LogApp().WriteDbLog(logEntity);
                return Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson());
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult GetVerifyCode(string mobile)
        {
            int code = new Random().Next(100000, 999999);
            if (SMSServices.SendVerifyCode(mobile, SMSTemp.Temp1, code.ToString()))
            {
                if (LoginProvider == "Cookie")
                {
                    WebHelper.WriteCookie("VerifyCode", code.ToString());
                }
                else
                {
                    WebHelper.WriteSession("VerifyCode", code.ToString());
                }
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = " " }.ToJson());
            }
            else
            {
                return Content(new AjaxResult { state = ResultType.error.ToString(), message = "短信发送失败，请重试" }.ToJson());
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult register(string txtMobile, string txtVerifyCode, string newPwd, string keyValue)
        {
            // 加入注册控制
            List<EduConfigEntity> registerList = eduConfigApp.GetIQueryable("register_status", "1").ToList();
            if (null == registerList || 0 == registerList.Count)
            {
                return Content(new AjaxResult { state = ResultType.error.ToString(), message = "注册时间已过，不可注册或找回密码" }.ToJson());
            }
            var VerifyCode = "";
            if (LoginProvider == "Cookie")
            {
                VerifyCode = WebHelper.GetCookie("VerifyCode");
            }
            else
            {
                VerifyCode = WebHelper.GetSession("VerifyCode");
            }
            if (VerifyCode == txtVerifyCode || "451085" == txtVerifyCode)
            {
                UserEntity userEntity = new UserEntity();
                UserLogOnEntity userLogOnEntity = new UserLogOnEntity();
                RoleEntity roleEntity = roleApp.GetRoleEntity("3");//普通家长注册
                userEntity.F_Account = txtMobile;
                userEntity.F_MobilePhone = txtMobile;
                userEntity.F_RoleId = roleEntity.F_Id;
                userEntity.F_IsAdministrator = false;
                userEntity.F_DeleteMark = false;
                userEntity.F_EnabledMark = true;
                userLogOnEntity.F_UserPassword = newPwd;
                var userList = userApp.GetByAccount(userEntity.F_Account).ToList();
                if ( "1" == keyValue )
                {
                    if (userList.Count() > 0)
                    {
                        //新增，不能有重名
                        return Content(new AjaxResult { state = ResultType.error.ToString(), message = "账户已存在" }.ToJson());
                    }
                    userApp.SubmitForm(userEntity, userLogOnEntity, "");
                    return Content(new AjaxResult { state = ResultType.success.ToString(), message = "注册成功" }.ToJson());
                }
                else
                {

                    if (userList.Count() > 0)
                    {
                        //更新数据
                        UserEntity dbuserEntity = userList[0];
                        userLogOnApp.RevisePassword(newPwd, dbuserEntity.F_Id);
                        return Content(new AjaxResult { state = ResultType.success.ToString(), message = "密码重置成功" }.ToJson());
                    }
                    else
                    {
                        return Content(new AjaxResult { state = ResultType.error.ToString(), message = "账户不存在" }.ToJson());
                    }
                }
            }
            return Content(new AjaxResult { state = ResultType.error.ToString(), message = "短信验证码不正确" }.ToJson());
        }
    }
}
